package com.starview.platform.resource;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import com.starview.platform.data.value.ResourceURI;
import com.starview.star.StarRules;

public class StdTransducer implements Transducer
{
  @Override
  public Reader getReader(ResourceURI uri) throws ResourceException
  {
    String fullResourceName = uri.getPath();
    InputStream istream = StarRules.class.getResourceAsStream(fullResourceName);

    if (istream == null && !fullResourceName.startsWith("/")) {
      fullResourceName = "/" + fullResourceName;
      istream = StarRules.class.getResourceAsStream(fullResourceName);
    }
    if (istream != null)
      return new InputStreamReader(istream);
    else
      throw new ResourceException(uri + " not accessable");
  }

  @Override
  public InputStream getInputStream(ResourceURI uri) throws ResourceException
  {
    String fullResourceName = uri.getPath();
    InputStream istream = StarRules.class.getResourceAsStream(fullResourceName);

    if (istream == null && !fullResourceName.startsWith("/")) {
      fullResourceName = "/" + fullResourceName;
      istream = StarRules.class.getResourceAsStream(fullResourceName);
    }
    if (istream != null)
      return istream;
    else
      throw new ResourceException(uri + " not accessable");
  }

  @Override
  public boolean exists(ResourceURI uri) throws ResourceException
  {
    String path = uri.getPath();
    if (StarRules.class.getResource(path) != null)
      return true;
    else
      return false;
  }

  @Override
  public void putResource(ResourceURI uri, Object resource) throws ResourceException
  {
    throw new ResourceException("not permitted");
  }
}